const { log } = require('debug');
var express = require('express');
var router = express.Router();
const Order = require('../model/db')

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/saveorder', (req, res) => {  // 添加的路由
  let obj = req.body
  console.log(obj);
  Order.find({ order: obj.order }).then(data => { //判断是否重复的
    if (data.length > 0) {
      res.send({ status: 200, success: false, msg: '该订单已存在！' })
    } else {
      Order.create(obj).then(() => {
        res.send({ status: 200, success: true, msg: '保存成功' })
      }).catch(() => {
        res.send({ status: 404, success: false, msg: '保存失败' })
      })
    }
  })
})



router.get('/getlist', (req, res) => { //查找的路由
  let re = new RegExp(req.query.search,'g') // 后端接收 前端传入的他的search

  Order.find({order:re}).then((data) => {
    res.send({ status: 200, success: true, msg: '查找成功', list: data })
  }).catch(() => {
    res.send({ status: 404, success: false, msg: '查找失败' })
  })
})


router.get('/delect', (req, res) => {//删除的路由
  let obj = req.query.id
  console.log(obj);
  Order.remove({ _id: req.query.id }).then(() => {
    res.send({ status: 200, success: true, msg: '删除成功', })
  }).catch(() => {
    res.send({ status: 404, success: false, msg: '删除失败' })
  }) 
 
 
})

router.post('/updata',(req,res)=>{ //修改的路由 
let id = req.body.id;
let obj = req.body.upData;
Order.update({ _id:id},{$set:obj}).then(() => {
  res.send({ status: 200, success: true, msg: '修改成功', })
}).catch(() => {
  res.send({ status: 404, success: false, msg: '修改失败' })
}) 
})

module.exports = router;
